package gw.com.android.ui.views;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.ui.trade.TradeRangeModel;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.util.DoubleConverter;
import www.com.library.view.BtnClickListener;
import www.com.library.view.NumberInput;
import www.com.library.view.TintImageView;

/**
 * 止损止盈自定义视图
 * 
 * @author reeta
 * 
 */
public class OrderBottomView extends LinearLayout {

	@BindView(R.id.tv_pice)
	TextView mPricView;
	/** 止损title */
	@BindView(R.id.morder_title_loss)
	TitleRangeView mOrderTitleLoss;
	/** 止盈title */
	@BindView(R.id.morder_title_win)
	TitleRangeView mOrderTitleWin;
	/** 点数设置title */
	@BindView(R.id.morder_type_switch)
	CheckBoxView mTypeSwitch;
	/** 止损加减器 */
	@BindView(R.id.morder_input_loss)
	NumericEdit mLossEditView = null;
	/** 止盈加减器title */
	@BindView(R.id.morder_input_win)
	NumericEdit mWinEditView = null;
	/**下拉和收起箭头*/
	@BindView(R.id.arraw_up)
	TintImageView mArrow;
	@BindView(R.id.morder_container_loss)
	View mLossLayout;
	@BindView(R.id.morder_container_win)
	View mWinLayout;

	private int mDigits = 8;
	private LayoutInflater mInflater;
	/** 焦点清理监听对象 */
	public onClearFocusLisenter mLisenter;
	/** 错误检查监听对象 */
	public onErrorCheckLisenter mErrorCheckLisenter;
    /**止损止盈范围值*/
	private TradeRangeModel mRangeModel;

	/**
	 * 更新通知处理
	 */
	public final Handler HandlerCallback = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GTSConst.REPLY_SYMBOL_TICK_UPDATE:
				// 更新止损止盈值
				if (null != mErrorCheckLisenter) {
					mErrorCheckLisenter.onErrorCheck();
				}
				break;
			}
		}
	};

	public OrderBottomView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	public OrderBottomView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public OrderBottomView(Context context) {
		super(context);
		initView(context);
	}

	/**
	 * 初始化界面元素
	 * 
	 * @param context
	 */
	private void initView(Context context) {
		mInflater = LayoutInflater.from(context);
		View convertView = mInflater.inflate(R.layout.order_bottom_view, this, true);
		ButterKnife.bind(this, convertView);

		mOrderTitleLoss.setTitleView(R.string.order_title_loss);
		mOrderTitleWin.setTitleView(R.string.order_title_profit);
		mTypeSwitch.setLeftResource(R.string.order_title_price);
		mTypeSwitch.setRightResource(R.string.order_title_point);
		mTypeSwitch.setChecked(false);
		mLossEditView.getNumericInput().setHint(R.string.order_title_empty);
		mWinEditView.getNumericInput().setHint(R.string.order_title_empty);
		mArrow.setVisibility(View.GONE);

		mLossEditView.setAfterTextChangedListener(new NumberInput.OnTextChangedListener() {
			@Override
			public void onTextChanged(EditText edit, Editable s) {
				String value = s.toString();
				if (value.length() < 1
						|| DoubleConverter.toDoubleData(value) == 0) {
				}
				if (HandlerCallback != null) {
					HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
				}
			}
		});
		mWinEditView.setAfterTextChangedListener(new NumberInput.OnTextChangedListener() {
			@Override
			public void onTextChanged(EditText edit, Editable s) {
				String value = s.toString();
				if (value.length() < 1
						|| DoubleConverter.toDoubleData(value) == 0) {
				}
				if (HandlerCallback != null) {
					HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
				}
			}
		});

		mTypeSwitch.setBtnClickListener(new BtnClickListener() {
			@Override
			public void onBtnClick(int viewID) {
				onDisplayOpenRanges();
				//价格--点数
				if(viewID == R.id.btn_right){
					mLossEditView.setPointVisible(View.VISIBLE);
					mWinEditView.setPointVisible(View.VISIBLE);
					changePriceToPoint();
				}else{
					//点数--价格
					mLossEditView.setPointVisible(View.GONE);
					mWinEditView.setPointVisible(View.GONE);
					changePointToPrice();
				}
				clearAllFocus();
				if (null != mLisenter) {
					mLisenter.onClearFocus();
				}
				if (null != mErrorCheckLisenter) {
					mErrorCheckLisenter.onErrorCheck();
				}
			}
		});
		mRangeModel = new TradeRangeModel();
	}

	@OnClick(R.id.arraw_up)
	void onFoldView(){
		setFoldView(mLossLayout.getVisibility() == View.GONE);
	}

	/**
	 * 设置止损止盈布局是否展开，true标识展开，false标识收起
	 * @param isFold
     */
	public void setFoldView(boolean isFold){
		mArrow.setVisibility(View.VISIBLE);
		if (isFold) {
			mLossLayout.setVisibility(View.VISIBLE);
			mWinLayout.setVisibility(View.VISIBLE);
			mTypeSwitch.setVisibility(View.VISIBLE);
			mArrow.setImageResource(R.mipmap.a_small_developup);
			mArrow.setColorValue(ColorThemeUtil.instance().color_k, ColorThemeUtil.instance().color_l);
		} else {
			mLossLayout.setVisibility(View.GONE);
			mWinLayout.setVisibility(View.GONE);
			mTypeSwitch.setVisibility(View.GONE);
			mArrow.setImageResource(R.mipmap.a_small_developdown);
			mArrow.setColorValue(ColorThemeUtil.instance().color_k, ColorThemeUtil.instance().color_l);
		}
	}

	/**
	 * 设置产品信息和界面其他信息
	 * 
	 * @param model 产品对象
	 */
	public void setProductInfo(TradeRangeModel model) {
		if(null != model){
			updateProduct(model);
		}
		resetLossAndWin();
	}

	/**
	 * 更新产品信息
	 *
	 * @param model
	 */
	public void updateProduct(TradeRangeModel model) {
		if (null != model) {
			mRangeModel = model;
			onDisplayOpenRanges();
		}
	}

	/**
	 * 止损止盈范围值更新调整
	 */
	public void onDisplayOpenRanges() {
		if(isPointType()){
			mOrderTitleLoss.setRangeView(mRangeModel.minPips, mRangeModel.maxPips);
			mOrderTitleWin.setRangeView(mRangeModel.minPips, mRangeModel.maxPips);
			mLossEditView.setMinSteps(1);
			mWinEditView.setMinSteps(1);
			mLossEditView.setMin(DoubleConverter.toDoubleData(mRangeModel.minPips));
			mLossEditView.setMax(DoubleConverter.toDoubleData(mRangeModel.maxPips));
			mWinEditView.setMin(DoubleConverter.toDoubleData(mRangeModel.minPips));
			mWinEditView.setMax(DoubleConverter.toDoubleData(mRangeModel.maxPips));
			if(mRangeModel.maxPips.contains(".")){
				int digit = mRangeModel.maxPips.length() - mRangeModel.maxPips.indexOf(".") - 1;
				int num = mRangeModel.maxPips.length() - digit - 1;
				Logger.e("点数后的位数为 ： " + (mRangeModel.maxPips.length()) +", " + (num) + ", "+ digit);
				mLossEditView.setDigits(mRangeModel.maxPips.length(), num, digit);
				mWinEditView.setDigits(mRangeModel.maxPips.length(), num, digit);
			}else{
				mLossEditView.setDigits(mRangeModel.maxPips.length(), mRangeModel.maxPips.length(), 0);
				mWinEditView.setDigits(mRangeModel.maxPips.length(), mRangeModel.maxPips.length(), 0);
			}
			mLossEditView.setDefalutValue(mRangeModel.defalutLossPoint);
			mWinEditView.setDefalutValue(mRangeModel.defalutWinPoint);
		}else{
			mOrderTitleLoss.setRangeView(mRangeModel.minRangeLoss, mRangeModel.maxRangeLoss);
			mOrderTitleWin.setRangeView(mRangeModel.minRangeWin, mRangeModel.maxRangeWin);
			mLossEditView.setMinSteps(mRangeModel.pointToPrice);
			mWinEditView.setMinSteps(mRangeModel.pointToPrice);
			mLossEditView.setMin(Double.MIN_VALUE);
			mLossEditView.setMax(Double.MAX_VALUE);
			mWinEditView.setMin(Double.MIN_VALUE);
			mWinEditView.setMax(Double.MAX_VALUE);
			Logger.e("价格后的位数为 ： " + 10 +", " + (9-mRangeModel.mDigit) + ", "+ mRangeModel.mDigit);
			mLossEditView.setDigits(10, (9-mRangeModel.mDigit), mRangeModel.mDigit);
			mWinEditView.setDigits(10, (9-mRangeModel.mDigit), mRangeModel.mDigit);

			mLossEditView.setDefalutValue(mRangeModel.defalutLossPrice);
			mWinEditView.setDefalutValue(mRangeModel.defalutWinPrice);
		}

		if (HandlerCallback != null) {
			HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
		}
	}

	/**
	 * 点数转成价格
	 */
	private void changePointToPrice(){
		if(!mLossEditView.isEmpty() && !mLossEditView.isEmptyOrZero(mDigits)){
			mLossEditView.setText(TradeBusiness.lossPointToPrice(mLossEditView.getValueString(), mRangeModel)+"");
		}else{
			mLossEditView.setText("");
		}

		if(!mWinEditView.isEmpty() && !mWinEditView.isEmptyOrZero(mDigits)){
			mWinEditView.setText(TradeBusiness.profitPointToPrice(mWinEditView.getValueString(), mRangeModel)+"");
		}else{
			mWinEditView.setText("");
		}
	}

    /**
	 * 价格转成点数
	 */
	private void changePriceToPoint(){
		if(!mLossEditView.isEmpty() && !mLossEditView.isEmptyOrZero(mDigits)){
			mLossEditView.setText(TradeBusiness.lossPriceToPoint(mLossEditView.getValueString(), mRangeModel)+"");
		}else{
			mLossEditView.setText("");
		}

		if(!mWinEditView.isEmpty() && !mWinEditView.isEmptyOrZero(mDigits)){
			mWinEditView.setText(TradeBusiness.profitPriceToPoint(mWinEditView.getValueString(), mRangeModel)+"");
		}else{
			mWinEditView.setText("");
		}
	}

	/**
	 * 设置价格和（价格点数）的显示
	 * 
	 * @param isShow
	 */
	public void setPriceType(boolean isShow) {
		if (isShow) {
			setViewVisibility(mPricView, true);
			setViewVisibility(mTypeSwitch, false);
			mTypeSwitch.setChecked(false);
		} else {
			setViewVisibility(mPricView, false);
			setViewVisibility(mTypeSwitch, true);
		}
	}

	/**
	 * 设置止损止盈的类型，0标识价格，1标识点数
	 * @param priceType
     */
	public void setPriceType(int priceType){
		if(priceType == 0){
			mTypeSwitch.setChecked(false);
		}else{
			mTypeSwitch.setChecked(true);
		}
	}

	/**
	 * 设置止损值
	 * @param price
     */
	public void setLossValue(String price){
		mLossEditView.setText(price);
	}

	/**
	 * 设置止盈值
	 * @param price
     */
	public void setProfitValue(String price){
		mWinEditView.setText(price);
	}

	/**
	 * 返回止损价格
	 * @return
     */
	public String getLossPrice(){
		if(isPointType()){
			if(!mLossEditView.isEmpty() && !mLossEditView.isEmptyOrZero(mDigits)){
				return TradeBusiness.lossPointToPrice(mLossEditView.getValueString(), mRangeModel)+"";
			}
			return mLossEditView.getValueString();
		}else{
			return mLossEditView.getValueString();
		}
	}

	/**
	 * 返回止盈价格
	 * @return
     */
	public String getWinPrice(){
		if(isPointType()){
			if(!mWinEditView.isEmpty() && !mWinEditView.isEmptyOrZero(mDigits)){
				return TradeBusiness.profitPointToPrice(mWinEditView.getValueString(), mRangeModel)+"";
			}
			return mWinEditView.getValueString();
		}else{
			return mWinEditView.getValueString();
		}
	}

	private void setViewVisibility(View v, boolean visible) {
		v.setVisibility(visible ? View.VISIBLE : View.GONE);
	}

	/**
	 * 返回当前是价格还是点数类型，true标识点数，false标识价格
	 * @return
     */
	public boolean isPointType(){
        if(mTypeSwitch.mRightBtn.isSelected()){
			return true;
		}

		return false;
	}

	/**
	 * 检查止损止盈的错误，true标识返回错误，fasle标识无错误
	 * @return
     */
	public String checkError(){
		String errorMessage = "";
//		Logger.e(mLossEditView.isEmpty() +", " + mLossEditView.isEmptyOrZero(mDigits) + ",");
		if(!mLossEditView.isEmpty() && !mLossEditView.isEmptyOrZero(mDigits)){
			String errorMessage1 = getLossErrorMsg();
			if(!"".equals(errorMessage1)){
				mOrderTitleLoss.setErrorColor();
				errorMessage = errorMessage1;
			}else {
				mOrderTitleLoss.setDefalutColor();
			}
		}else {
			mOrderTitleLoss.setDefalutColor();
		}

		if(!mWinEditView.isEmpty() && !mWinEditView.isEmptyOrZero(mDigits)){
			String errorMessage2 = getWinErrorMsg();
			if(!"".equals(errorMessage2)){
				mOrderTitleWin.setErrorColor();
				if("".equals(errorMessage)){
					errorMessage = errorMessage2;
				}
			}else {
				mOrderTitleWin.setDefalutColor();
			}
		}else {
			mOrderTitleWin.setDefalutColor();
		}

		return errorMessage;
	}

	private String getLossErrorMsg(){
		if(isPointType()){
			return TradeBusiness.getLossPointErrorMsg(mRangeModel.minPips, mRangeModel.maxPips, mLossEditView.getValueString());
		}else{
			return TradeBusiness.getLossPriceErrorMsg(mRangeModel.minRangeLoss, mRangeModel.maxRangeLoss, mLossEditView.getValueString());
		}
	}

	private String getWinErrorMsg(){
		if(isPointType()){
			return TradeBusiness.getWinPointErrorMsg(mRangeModel.minPips, mRangeModel.maxPips, mWinEditView.getValueString());
		}else{
			return TradeBusiness.getWinPriceErrorMsg(mRangeModel.minRangeWin, mRangeModel.maxRangeWin, mWinEditView.getValueString());
		}
	}

	/**
	 * 为输入框添加焦点监听事件
	 * 
	 * @param listener
	 */
	public void setFocusChange(OnFocusChangeListener listener) {
		mLossEditView.getNumericInput().setOnFocusChangeListener(listener);
		mWinEditView.getNumericInput().setOnFocusChangeListener(listener);
	}

	/**
	 * 重置止损止盈编辑框的值为空
	 */
	public void resetLossAndWin() {
		mLossEditView.setText("");
		mWinEditView.setText("");
	}

	/**
	 * 返回止损编辑框
	 *
	 * @return
	 */
	public NumberInput getLossInput() {
		return mLossEditView.getNumericInput();
	}

	/**
	 * 返回止盈编辑框
	 *
	 * @return
	 */
	public NumberInput getWinInput() {
		return mWinEditView.getNumericInput();
	}

	/**
	 * 返回下单类型，0表示点数，1表示价格
	 * 
	 * @return
	 */
	public boolean getPointType() {
		return mTypeSwitch.mRightBtn.isSelected();
	}

	/**
	 * 焦点改变逻辑
	 * 
	 * @param v
	 */
	public void onFocusChanged(View v, boolean hasFocus) {
		if (v == getLossInput() && getPointType()) {
			getLossInput().setText(getLossInput().getTextValue());
		} else if (v == getWinInput() && getPointType()) {
			getWinInput().setText(getWinInput().getTextValue());
		}
	}

	/**
	 * 清理界面焦点
	 */
	public void clearAllFocus() {
		getLossInput().clearFocus();
		getWinInput().clearFocus();
	}

	/**
	 * 焦点清理监听对象设置
	 * 
	 * @param lisenter
	 */
	public void setErrorCheckLisenter(onErrorCheckLisenter lisenter) {
		mErrorCheckLisenter = lisenter;
	}

	/**
	 * 清空焦点监听
	 * 
	 * @author Administrator
	 * 
	 */
	public interface onErrorCheckLisenter {
		/**
		 * 清空焦点的方法
		 */
		void onErrorCheck();
	}

	/**
	 * 焦点清理监听对象设置
	 * 
	 * @param lisenter
	 */
	public void setClearFocusLisenter(onClearFocusLisenter lisenter) {
		mLisenter = lisenter;
	}

	/**
	 * 清空焦点监听
	 * 
	 * @author Administrator
	 * 
	 */
	public interface onClearFocusLisenter {
		/**
		 * 清空焦点的方法
		 */
		void onClearFocus();
	}
}
